package com.rxt.thermopro.ui.fragment

import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Matrix
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.app.common.base.BaseFragment
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.github.mikephil.charting.listener.ChartTouchListener
import com.github.mikephil.charting.listener.OnChartGestureListener
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.Utils
import com.rxt.thermopro.R
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.ProbeBean
import com.rxt.thermopro.bean.TempHumBean
import com.rxt.thermopro.ui.chart.MyMarkerView
import com.rxt.thermopro.viewmodel.BleMessageViewModel
import com.rxt.thermopro.viewmodel.DataChartsViewModel
import com.rxt.thermopro.viewmodel.DeviceStatusViewModel
import com.rxt.thermopro.viewmodel.EventViewModel
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_data_charts.*
import kotlinx.android.synthetic.main.fragment_data_charts.backButton
import kotlinx.android.synthetic.main.fragment_data_charts.viewBluetoothBBQ
import kotlinx.android.synthetic.main.fragment_data_charts.viewPhoneBBQ
import java.text.SimpleDateFormat
import java.util.*


class DataChartsFragment : BaseFragment<DataChartsViewModel>(), OnChartValueSelectedListener {
    override fun layoutId(): Int {
        return R.layout.fragment_data_charts
    }

    companion object {
        private const val ARG_DEVICE_NAME = "deviceName"
        private const val ARG_DEVICE_ADDRESS = "address"

        fun newInstance(deviceName: String, address: String): DataChartsFragment {
            return DataChartsFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_DEVICE_NAME, deviceName)
                    putString(ARG_DEVICE_ADDRESS, address)
                }
            }
        }
    }

    private var mData = ProbeBean()
    private lateinit var mDeviceStatusViewModel: DeviceStatusViewModel
    private lateinit var mBleViewModel: BleMessageViewModel
    private lateinit var mEventViewModel: EventViewModel
    private val refreshTempDataCache = mutableListOf<ProbeBean>()
    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")

    override fun onResume() {
        super.onResume()
        if (refreshTempDataCache.isNotEmpty()) {
            mBleViewModel.notifyMsgData.value =
            hashMapOf<Long, MutableList<ProbeBean>>().apply {
                this[System.currentTimeMillis()] = mutableListOf<ProbeBean>().apply {
                    this.addAll(refreshTempDataCache)
                }
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDeviceStatusViewModel =
            ViewModelProvider(requireActivity()).get(DeviceStatusViewModel::class.java)
        mBleViewModel =
            ViewModelProvider(requireActivity()).get(BleMessageViewModel::class.java)
        mEventViewModel = ViewModelProvider(requireActivity()).get(EventViewModel::class.java)
        val deviceName = arguments?.getString(ARG_DEVICE_NAME, "") ?: ""
        val address = arguments?.getString(ARG_DEVICE_ADDRESS, "") ?: ""
        mData.address = address
        mData.name = deviceName
        tempUnit.text = String.format(
            getString(R.string.text_temp_line_unit),
            LocalDataDao.INSTANCE.getTempUnit()
        )

        //信号 电量
        if (mBleViewModel.signalLevelCache.isNotEmpty() &&
            mBleViewModel.signalLevelCache.containsKey(mData.address)
        ) {
            val signal = mBleViewModel.signalLevelCache[mData.address] ?: -100
            setSignal(signal)
            viewBluetoothBBQ.isSelected = signal != -100
        }

        mBleViewModel.loadCacheData.observeInFragment(this, Observer {
//            if (mBleViewModel.notifyInfoDataCache.isNotEmpty()) {
//                setBatteryLevel(mBleViewModel.notifyInfoDataCache.last().second.electricity.toInt())
//            }
            if (mBleViewModel.signalLevelCache.isNotEmpty() &&
                mBleViewModel.signalLevelCache.containsKey(mData.address)
            ) {
                val signal = mBleViewModel.signalLevelCache[mData.address] ?: -100
                setSignal(signal)
                viewBluetoothBBQ.isSelected = signal != -100
            }
            if (mBleViewModel.notifyMsgDataCache.containsKey(mData.address) &&
                mBleViewModel.notifyMsgDataCache[mData.address]?.isNotEmpty() == true
            ) {
                mBleViewModel.notifyMsgDataCache[mData.address]?.let { itList ->
                    updateTemp(itList)
                }
            }
        })

        mBleViewModel.signalLevel.observeInFragment(this, Observer {
            if (it.values.last().containsKey(mData.address)) {
                println("=====>  setSignal $it")
                val signal = it.values.last()[mData.address] ?: -100
                viewBluetoothBBQ.isSelected = signal != -100
            }
        })

        mBleViewModel.connectSuccess.observeInFragment(this, Observer {
            //连接成功 可以获取数据了
            mBleViewModel.tempDataSize = 0
            mViewModel.getTempHistory(1, mData.address)
        })

        mBleViewModel.notifyRefreshTempData.observeForever(Observer {
            if (it.last().address == mData.address) {
                refreshTempDataCache.clear()
                refreshTempDataCache.addAll(it)
            }
        })

        mBleViewModel.notifyMsgData.observeInFragment(this, Observer { item->
            val it=item.values.last()
            if (it.last().address == mData.address) {
                updateTemp(it)
            }
        })

        /**
         * 历史数据
         */
        mBleViewModel.notifyHistoryTempTP359Data.observeInFragment(this, Observer {
            println("======>  notifyHistoryTempTP359Data=$it")
            val list = it[it.keys.last()] ?: mutableListOf()
            if (LocalDataDao.INSTANCE.getTempUnit() == LocalDataDao.TEMP_UNIT_F) {
                val newList = mutableListOf<TempHumBean>()
                for (i in 0 until list.size) {
                    val newBean = TempHumBean()
                    newBean.tempNum =
                        LocalDataDao.INSTANCE.transUnitCToF(list[i].tempNum)
                    newBean.tempTime = list[i].tempTime
                    newList.add(newBean)
                }
                setChart(chart1, newList, it.keys.last())
                setChart(chart2, newList, it.keys.last())
            } else {
                setChart(chart1, list, it.keys.last())
                setChart(chart2, list, it.keys.last())
            }
        })

        mDeviceStatusViewModel.removeDevice.observeInFragment(this, Observer {
            if (it.values.contains(mData.address)) {
                requireActivity().onBackPressed()
            }
        })

        mBleViewModel.connectBluetooth(mData)

//        setChart(chart1)
//        setChart(chart2)
        refreshLayout.setRefreshHeader(ClassicsHeader(requireContext()))
        initListener()
    }

    private fun setSignal(signal: Int) {
        when (signal) {
            in -100..-90 -> {
                viewPhoneBBQ.setImageResource(R.drawable.main_not_connected)
            }
            in -90..-80 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_weak)
            }
            in -80..-70 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_mid2)
            }
            in -70..-60 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_mid1)
            }
            in -60..-50 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_strong2)
            }
            in -50..0 -> {
                viewPhoneBBQ.setImageResource(R.drawable.signal_strong1)
            }
        }
    }

    /**
     * 更新温湿度数据
     */
    private fun updateTemp(it: MutableList<ProbeBean>) {
        temperatureNum.text = LocalDataDao.INSTANCE.convertUnit(it.last().temperatureNUm).let {
            if (it.isEmpty()) {
                "--" + LocalDataDao.INSTANCE.getTempUnit()
            } else {
                it
            }
        }
        humidityNum.text = it.last().humidityNum.let {
            if (it.isEmpty()) {
                "--" + "%"
            } else {
                "$it%"
            }
        }
        heatIndexNum.text = LocalDataDao.INSTANCE.convertUnit(it.last().heatIndex).let {
            if (it.isEmpty()) {
                "--" + LocalDataDao.INSTANCE.getTempUnit()
            } else {
                it
            }
        }
    }

    private fun initListener() {
        backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        viewEdit.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    DeviceSettingFragment.newInstance(mData.name,mData.address)
                )
                .addToBackStack("main")
                .commit()
        }

        probeView.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.checkHour -> {
                    mViewModel.getTempHistory(1, mData.address)
                }
                R.id.checkWeek -> {
                    mViewModel.getTempHistory(2, mData.address)
                }
                R.id.checkYear -> {
                    mViewModel.getTempHistory(3, mData.address)
                }
            }
        }
    }

    private fun setChart(mChart: LineChart, list: MutableList<TempHumBean>, type: Int) {
        var maxYValue = 0f
        var minYValue = 0f
        if (mChart == chart1) {
            for (i in 0 until list.size) {
                val tempNum = if (list[i].tempNum.isNotEmpty()) list[i].tempNum.toFloat() else 0f
                if (i == 0) {
                    maxYValue = tempNum
                    minYValue = tempNum
                }
                if (i > 0) {
                    if (maxYValue < tempNum) {
                        maxYValue = tempNum
                    }
                    if (minYValue > tempNum) {
                        minYValue = tempNum
                    }
                }
            }
        } else {
            for (i in 0 until list.size) {
                val humidityNum =
                    if (list[i].humidityNum.isNotEmpty()) list[i].humidityNum.toFloat() else 0f
                if (i == 0) {
                    maxYValue = humidityNum
                    minYValue = humidityNum
                }
                if (i > 0) {
                    if (maxYValue < humidityNum) {
                        maxYValue = humidityNum
                    }
                    if (minYValue > humidityNum) {
                        minYValue = humidityNum
                    }
                }
            }
        }

        mChart.apply {
            // background color
            setBackgroundColor(Color.WHITE)
            // disable description text
            description.isEnabled = false
            // enable touch gestures
            setTouchEnabled(true)
            // set listeners
            if (mChart == chart1) {
                setOnChartValueSelectedListener(this@DataChartsFragment)
                onChartGestureListener = CoupleChartGestureListener(mChart, arrayOf(chart2))
                // create marker to display box when values are selected
                val mv = MyMarkerView(requireContext(), R.layout.custom_marker_view, list)
                // Set the marker to the chart
                mv.chartView = this
                marker = mv
            } else {
                setOnChartValueSelectedListener(chartSelectListener)
                onChartGestureListener = CoupleChartGestureListener(mChart, arrayOf(chart1))
            }

            setDrawGridBackground(true)

            // enable scaling and dragging
            isDragEnabled = true
            setScaleEnabled(true)
            isScaleXEnabled = true
            isScaleYEnabled = false
            // force pinch zoom along both axis
            setPinchZoom(true)
            legend.isEnabled = false

        }

        var xAxis: XAxis = chart1.xAxis
        // // X-Axis Style // //
        xAxis = mChart.xAxis
        xAxis.setDrawAxisLine(true)
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.axisMinimum = 0f;
        xAxis.granularity = 1f;
        // vertical grid lines
        xAxis.setGridDashedLine(null)
//        xAxis.enableGridDashedLine(10f, 10f, 0f)
        if (type == 3) {
            xAxis.setLabelCount(8, false)
        } else {
            xAxis.setLabelCount(8, true)
        }

        if (list.size < 8) {
            xAxis.axisMaximum = 8f
        } else {
            xAxis.axisMaximum = list.size.toFloat()
        }

        when (type) {
            1 -> {
                xAxis.setValueFormatter { value, _ ->
//            println("============>setValueFormatter value=$value")
                    var str = ""
                    when {
                        list.isEmpty() -> {
                            val date = Date()
                            date.time = (System.currentTimeMillis() + 60L * 1000 * value).toLong()
                            val timeStr = dateFormat.format(date)
                            str = timeStr.split(" ")[1]
                        }
//                list.size < 8 -> {
//                    val listSize = list.size
//                    val tempTime =
//                        if (value.toInt() >= listSize) (list.last().tempTime.toLong() + (value - listSize + 1).toLong() * 75L * 1000L).toString()
//                        else list[value.toInt()].tempTime
//                    val date = Date()
//                    date.time = tempTime.toLong()
//                    val timeStr = dateFormat.format(date)
//                    str = timeStr.split(" ")[1]
//                }
                        else -> {
                            val listSize = list.size
                            val tempTime =
                                if (value.toInt() >= listSize) (list.last().tempTime.toLong() + (value - listSize + 1).toLong() * 60L * 1000L).toString()
                                else list[value.toInt()].tempTime
                            val date = Date()
                             tempTime.toLongOrNull()?.let {
                                 date.time =it
                            }
                            val timeStr = dateFormat.format(date)
                            str = timeStr.split(" ")[1]
                        }
                    }
//            println("============>setValueFormatter=$str  timeStr=$timeStr value=$value")
                    str
                }
            }
            2 -> {
                xAxis.setValueFormatter { value, _ ->
                    var str = ""
                    when {
                        list.isEmpty() -> {
                            val date = Date()
                            date.time =
                                (System.currentTimeMillis() + 60 * 60 * 1000 * value).toLong()
                            val timeStr = dateFormat.format(date)
                            str = timeStr.split(" ")[1]
                        }
                        else -> {
                            val listSize = list.size
                            val tempTime =
                                if (value.toInt() >= listSize) (list.last().tempTime.toLong() +
                                        (value - listSize + 6).toLong() * 60 * 60 * 1000L).toString()
                                else list[value.toInt()].tempTime
                            val date = Date()
                            date.time = tempTime.toLong()
                            val calendar = Calendar.getInstance()
                            calendar.time = date
                            str = when (calendar.get(Calendar.DAY_OF_WEEK)) {
                                1 -> "Mon."
                                2 -> "Tue."
                                3 -> "Wed."
                                4 -> "Thur."
                                5 -> "Fri."
                                6 -> "Sat."
                                7 -> "Sun."
                                else -> "no data"
                            }
                        }
                    }
                    str
                }
            }
            3 -> {
                xAxis.setValueFormatter { value, _ ->
                    var str = ""
                    when {
                        list.isEmpty() -> {
                            val date = Date()
                            date.time =
                                (System.currentTimeMillis() + 60 * 60 * 1000 * value).toLong()
                            val timeStr = dateFormat.format(date)
                            str = timeStr.split(" ")[1]
                        }
                        else -> {
                            val listSize = list.size
                            val tempTime =
                                if (value.toInt() >= listSize) (list.last().tempTime.toLong() +
                                        (value - listSize + 6).toLong() * 60 * 60 * 1000L).toString()
                                else list[value.toInt()].tempTime
                            val date = Date()
                            date.time = tempTime.toLong()
                            val timeStr = dateFormat.format(date)
                            str = timeStr.split(" ")[1]
                        }
                    }
                    str
                }
            }
        }


        // // Y-Axis Style // //
        val yAxis: YAxis = mChart.axisLeft

        // disable dual axis (only use LEFT axis)
        mChart.axisRight.isEnabled = false

        // horizontal grid lines
        yAxis.setGridDashedLine(null)
        yAxis.setLabelCount(7, true)
//        yAxis.enableGridDashedLine(10f, 10f, 0f)
        // axis range
        if (mChart == chart1) {
            when (type) {
                1 -> {
                    yAxis.axisMaximum = maxYValue + 0.1f
                    yAxis.axisMinimum = minYValue - 0.1f
                }
                2 -> {
                    yAxis.axisMaximum = maxYValue + 0.5f
                    yAxis.axisMinimum = minYValue - 0.3f
                }
                3 -> {
                    yAxis.axisMaximum = maxYValue + 0.5f
                    yAxis.axisMinimum = minYValue - 0.3f
                }
            }

        } else {
            when (type) {
                1 -> {
                    yAxis.axisMaximum = maxYValue + 2f
                    yAxis.axisMinimum = minYValue - 2f
                }
                2 -> {
                    yAxis.axisMaximum = maxYValue + 1f
                    yAxis.axisMinimum = minYValue - 1f
                }
                3 -> {
                    yAxis.axisMaximum = maxYValue + 1f
                    yAxis.axisMinimum = minYValue - 1f
                }
            }
        }

        // draw limit lines behind data instead of on top
        yAxis.setDrawLimitLinesBehindData(true)
        xAxis.setDrawLimitLinesBehindData(true)


        // add data
//        setData(45, 100f, mChart)
        if (list.isNotEmpty()) {
            setData(list, mChart)
        }
        // draw points over time
        mChart.animateX(800)
        // get the legend (only possible after setting data)
        val l = mChart.legend
        // draw legend entries as lines
        l.form = Legend.LegendForm.LINE
    }


    private fun setData(list: MutableList<TempHumBean>, mChart: LineChart) {
        val values = ArrayList<Entry>()
        var maxYValue = 0f
        var minYValue = 0f
        if (mChart == chart1) {
            for (i in 0 until list.size) {
                val tempNum = if (list[i].tempNum.isNotEmpty()) list[i].tempNum.toFloat() else 0f
                values.add(
                    Entry(
                        i.toFloat(),
                        tempNum,
                        resources.getDrawable(R.mipmap.add_device_redpoint)
                    )
                )
                if (i == 0) {
                    maxYValue = tempNum
                    minYValue = tempNum
                }
                if (i > 0) {
                    if (maxYValue < tempNum) {
                        maxYValue = tempNum
                    }
                    if (minYValue > tempNum) {
                        minYValue = tempNum
                    }
                }
            }
        } else {
            for (i in 0 until list.size) {
                val humidityNum =
                    if (list[i].humidityNum.isNotEmpty()) list[i].humidityNum.toFloat() else 0f
                values.add(
                    Entry(
                        i.toFloat(),
                        humidityNum,
                        resources.getDrawable(R.mipmap.add_device_redpoint)
                    )
                )
                if (i == 0) {
                    maxYValue = humidityNum
                    minYValue = humidityNum
                }
                if (i > 0) {
                    if (maxYValue < humidityNum) {
                        maxYValue = humidityNum
                    }
                    if (minYValue > humidityNum) {
                        minYValue = humidityNum
                    }
                }
            }
        }

        val set1: LineDataSet
        if (mChart.data != null &&
            mChart.data.dataSetCount > 0
        ) {
            set1 = mChart.data.getDataSetByIndex(0) as LineDataSet
            set1.maxYValue = maxYValue
            set1.minYValue = minYValue
            set1.entries = values

            set1.notifyDataSetChanged()
            mChart.data.notifyDataChanged()
            mChart.notifyDataSetChanged()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(values, "DataSet 1")
            set1.maxYValue = maxYValue
            set1.minYValue = minYValue
            set1.setDrawIcons(false)

            // draw dashed line
//            set1.enableDashedLine(10f, 5f, 0f)
            set1.disableDashedLine()

            // black lines and points
            if (mChart == chart1) {
                set1.color = Color.BLUE
            } else {
                set1.color = Color.parseColor("#458B74")
            }
            set1.setCircleColor(Color.RED)

            // line thickness and point size
            set1.lineWidth = 1f
            set1.circleRadius = 3f

            // draw points as solid circles
            set1.setDrawCircleHole(true)
            set1.circleHoleColor = Color.WHITE

            // customize legend entry
            set1.formLineWidth = 1f
            set1.formLineDashEffect = DashPathEffect(floatArrayOf(10f, 5f), 0f)
            set1.formSize = 15f

            // text size of values
            set1.valueTextSize = 9f

            // draw selection line as dashed
//            set1.enableDashedHighlightLine(10f, 5f, 0f)
            set1.disableDashedHighlightLine()
            set1.setDrawHighlightIndicators(true)
            set1.setDrawHorizontalHighlightIndicator(false)
            set1.highlightLineWidth = 1F
            set1.highLightColor = Color.BLACK
            set1.setDrawValues(false)
            set1.setDrawCircles(false)

            // set the filled area
            set1.setDrawFilled(true)
            set1.fillFormatter =
                IFillFormatter { dataSet, dataProvider -> mChart.axisLeft.axisMinimum }

            // set color of filled area
            if (Utils.getSDKInt() >= 18) {
                // drawables only supported on api level 18 and above
                val drawable = ContextCompat.getDrawable(requireContext(), R.drawable.fade_blue)
                set1.fillDrawable = drawable
            } else {
                set1.fillColor = Color.BLACK
            }
            val dataSets = ArrayList<ILineDataSet>()
            dataSets.add(set1) // add the data sets

            // create a data object with the data sets
            val data = LineData(dataSets)

            // set data
            mChart.data = data
        }
    }

    override fun onValueSelected(e: Entry?, h: Highlight?) {
        Log.i("Entry selected", e.toString())
        Log.i("LOW HIGH", "low: " + chart1.lowestVisibleX + ", high: " + chart1.highestVisibleX)
        Log.i(
            "MIN MAX",
            "xMin: " + chart1.xChartMin + ", xMax: " + chart1.xChartMax + ", yMin: " +
                    chart1.yChartMin + ", yMax: " + chart1.yChartMax
        )
        chart1.setScaleEnabled(false)
        chart1.isScaleYEnabled = false
        chart1.isScaleXEnabled = false
        chart2.setScaleEnabled(false)
        chart2.isScaleYEnabled = false
        chart2.isScaleXEnabled = false

        val set1 = chart1.data.getDataSetByIndex(0) as LineDataSet
        val index = set1.entries.indexOf(e)

        val set2 = chart2.data.getDataSetByIndex(0) as LineDataSet
        val xValue = set2.entries[index].x
        val yValue = set2.entries[index].y
        chart2.highlightValue(xValue, yValue, 0, false)

        e?.icon = resources.getDrawable(R.mipmap.add_device_point, null)
        set1.notifyDataSetChanged()

    }

    override fun onNothingSelected() {
        chart1.setScaleEnabled(true)
        chart1.isScaleYEnabled = false
        chart1.isScaleXEnabled = true

        chart2.setScaleEnabled(true)
        chart2.isScaleYEnabled = false
        chart2.isScaleXEnabled = true

        chart2.highlightValue(null)

    }

    private val chartSelectListener = object : OnChartValueSelectedListener {
        override fun onValueSelected(e: Entry?, h: Highlight?) {
            Log.i("Entry selected chart2", e.toString())
            Log.i(
                "LOW HIGH chart2",
                "low: " + chart1.lowestVisibleX + ", high: " + chart1.highestVisibleX
            )
            Log.i(
                "MIN MAX chart2",
                "xMin: " + chart1.xChartMin + ", xMax: " + chart1.xChartMax + ", yMin: " +
                        chart1.yChartMin + ", yMax: " + chart1.yChartMax
            )
            chart1.setScaleEnabled(false)
            chart1.isScaleYEnabled = false
            chart1.isScaleXEnabled = false
            chart2.setScaleEnabled(false)
            chart2.isScaleYEnabled = false
            chart2.isScaleXEnabled = false


            val set1 = chart2.data.getDataSetByIndex(0) as LineDataSet
            val index = set1.entries.indexOf(e)

            val set2 = chart1.data.getDataSetByIndex(0) as LineDataSet
            val xValue = set2.entries[index].x
            val yValue = set2.entries[index].y
            chart1.highlightValue(xValue, yValue, 0, false)

        }

        override fun onNothingSelected() {
            chart1.setScaleEnabled(true)
            chart1.isScaleYEnabled = false
            chart1.isScaleXEnabled = true

            chart2.setScaleEnabled(true)
            chart2.isScaleYEnabled = false
            chart2.isScaleXEnabled = true

            chart1.highlightValue(null)


        }
    }

    inner class CoupleChartGestureListener(
        var srcChart: LineChart,
        var dstCharts: Array<LineChart>
    ) : OnChartGestureListener {
        override fun onChartGestureStart(
            me: MotionEvent?,
            lastPerformedGesture: ChartTouchListener.ChartGesture?
        ) {

        }

        override fun onChartGestureEnd(
            me: MotionEvent?,
            lastPerformedGesture: ChartTouchListener.ChartGesture?
        ) {

        }

        override fun onChartLongPressed(me: MotionEvent?) {

        }

        override fun onChartDoubleTapped(me: MotionEvent?) {

        }

        override fun onChartSingleTapped(me: MotionEvent?) {

        }

        override fun onChartFling(
            me1: MotionEvent?,
            me2: MotionEvent?,
            velocityX: Float,
            velocityY: Float
        ) {

        }

        override fun onChartScale(me: MotionEvent?, scaleX: Float, scaleY: Float) {
            syncCharts()
        }

        override fun onChartTranslate(me: MotionEvent?, dX: Float, dY: Float) {
            syncCharts()
        }

        fun syncCharts() {
            val srcValues = FloatArray(9)
            var dstMatrix: Matrix
            val dstValues = FloatArray(9)
            // get src chart translation matrix:
            val srcMatrix: Matrix = srcChart.viewPortHandler.matrixTouch
            srcMatrix.getValues(srcValues)
            // apply X axis scaling and position to dst charts:
            for (dstChart in dstCharts) {
                if (dstChart.visibility == View.VISIBLE) {
                    dstMatrix = dstChart.viewPortHandler.matrixTouch
                    dstMatrix.getValues(dstValues)
                    dstValues[Matrix.MSCALE_X] = srcValues[Matrix.MSCALE_X]
                    dstValues[Matrix.MTRANS_X] = srcValues[Matrix.MTRANS_X]
                    dstMatrix.setValues(dstValues)
                    dstChart.viewPortHandler.refresh(dstMatrix, dstChart, true)
                }
            }
        }
    }

}